package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Param;
import com.example.demo.ResultUtil;
import com.example.demo.ResultVO;
import com.example.demo.ali.HttpUtils;
import com.example.demo.baidu.AuthService;
import com.example.demo.baidu.util.Base64Util;
import com.example.demo.baidu.util.FileUtil;
import com.example.demo.baidu.util.HttpUtil;
import com.example.demo.ali.HttpClientUtils;
import com.example.demo.ali.HttpExecuteResponse;
import com.example.demo.huawei.ocr.HWOcrClientAKSK;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/demo")
public class DemoController {
    @PostMapping("/test")
    public ResultVO test(@RequestBody Param param) {
        System.out.println(param.getImage());

        String AK="NHZQMMF8WJW3XOH4IUUS"; //AK from authentication
        String SK="Ar5qhzwqMeHUpPiavD2nhXI4MMeLOXfwae8wYQml"; //SK from authentication
        String regionName="cn-north-4"; //region name of the service
//		String httpUri = "/v1.0/ocr/id-card";
        String httpUri = "/v2/cn-north-4/ocr/general-table";
        String imgPath = param.getImage(); //File path or URL of the image to be recognized.

        // Set params except image
//        String sideKey = "side";
//        String sideValue = "front";
        JSONObject params = new JSONObject();

        try {
            HWOcrClientAKSK ocrClient=new HWOcrClientAKSK(regionName, AK, SK);
            HttpResponse response=ocrClient.RequestOcrServiceBase64(httpUri, imgPath, params);
            System.out.println(response);
            String content = IOUtils.toString(response.getEntity().getContent(), "utf-8");
            System.out.println(content);
            return ResultUtil.succeeded(content);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.succeeded("失败了");

    }


    @PostMapping("/test2")
    public ResultVO test1(@RequestBody Param param) {
        System.out.println(param.getImage());
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/form";
        try {

            String imgParam = URLEncoder.encode(param.getImage(), "UTF-8");

            String param2 = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();

            String result = HttpUtil.post(url, accessToken, param2);
            System.out.println(result);
            return ResultUtil.succeeded(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultUtil.succeeded("失败了");
    }


    @PostMapping("/test3")
    public ResultVO test2(@RequestBody Param param) {
        String host = "https://form.market.alicloudapi.com";
        String path = "/api/predict/ocr_table_parse";
        String appcode = "fb333996b4a2419a86fc6d9fc06087fa";
        //String imgFile = "图片路径";
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("format", "json");
        configObj.put("finance", false);
        configObj.put("dir_assure", false);
        String config_str = configObj.toString();
        //            configObj.put("min_size", 5);
        //String config_str = "";

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();

        // 对图像进行base64编码
        String imgBase64 = param.getImage();
        /*try {
            File file = new File(imgFile);
            byte[] content = new byte[(int) file.length()];
            FileInputStream finputstream = new FileInputStream(file);
            finputstream.read(content);
            finputstream.close();
            imgBase64 = new String(encodeBase64(content));
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }*/
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if(is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if(config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            }else{
                requestObj.put("image", imgBase64);
                if(config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();
        String result = "";
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if(stat != 200){
                //System.out.println("Http code: " + stat);
                //System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
                //System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                return ResultUtil.failed(stat, EntityUtils.toString(response.getEntity()));
            }

            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);

            if(is_old_format) {
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject out = JSON.parseObject(output);
                result = out.toJSONString();
                System.out.println(out.toJSONString());
            }else{
                result = res_obj.toJSONString();
                System.out.println(res_obj.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.succeeded(result);
    }

    public static JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
